package com.example.ucs_alg_node_manager.utils;

import com.example.ucs_alg_node_manager.vo.SystemStatus;
import jakarta.annotation.Resource;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Component
public class RestTemplateUtil {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 不带参数的get请求
     * @return
     */
    public SystemStatus getWithoutParams(String url){
        return restTemplate.getForObject(url, SystemStatus.class);
    }

    /**
     * 带参数的get请求（restful风格）
     * @param uriVariables 请求参数
     * @return
     */
    public SystemStatus getWithParams(String url,Map uriVariables){
        return restTemplate.getForObject(url, SystemStatus.class, uriVariables);
    }

    public SystemStatus post(String url, Object data){
        return restTemplate.postForObject(url, data, SystemStatus.class);
    }

    public SystemStatus uploadFile(MultipartFile file) throws IOException {
        String fname = file.getOriginalFilename().substring(0, file.getOriginalFilename().length() - 4);
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 将 MultipartFile 转换为 Resource
        ByteArrayResource resource = new ByteArrayResource(file.getBytes()) {
            @Override
            public String getFilename() {
                return file.getOriginalFilename();
            }
        };

        // 构建 MultiValueMap
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", resource);
        body.add("fname", fname);

        // 构建请求实体
        HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(body, headers);

        // 发送请求
        return restTemplate.postForObject(UcsPatterns.UPLOAD_MODEL_URL,request, SystemStatus.class );
    }


}
